package com.xuzhiguang.lightnat.server.core.server.proxy.handler;

import com.xuzhiguang.lightnat.common.manager.ProxyChannelManager;
import com.xuzhiguang.lightnat.server.core.server.transfer.TransferChannelManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class WritabilityChangedHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {

        log.debug("proxy writability changed. channel:{}", ctx.channel());

        Long transferId = ProxyChannelManager.getTransferId(ctx.channel());

        if (transferId == null) {
            log.warn("transferId is null. channel:{}", ctx.channel());
        } else {
            Channel transferChannel = TransferChannelManager.getChannel(transferId);
            if (transferChannel == null) {
                log.warn("transferChannel is null. transferId:{}", transferId);
            } else {
                transferChannel.config().setAutoRead(ctx.channel().isWritable());
            }
        }

        super.channelWritabilityChanged(ctx);
    }
}
